<?php

/**
 * Tworzy URL z podanego tekstu
 *
 * @category   Core
 * @package    Core_Filter
 * @copyright  Copyright (c) 2008 Kuśmierz Adam
 * @author Adam Kuśmierz
 */

class Core_Filter_Preamble implements Zend_Filter_Interface
{
	/**
	 * Prospective Length of Preamble
	 * @var int
	 */
	protected $_preambleLength = 127;

	/**
	 * Constructor
	 *
	 * @param  string $preambleLength
	 * @return void
	 */
	public function __construct($preambleLength = null)
	{
		if ($preambleLength) {
			$this->setPreambleLength($preambleLength);
		}
	}

	/**
	 * Prospective preamble length
	 *
	 * @param int $length
	 * @return Core_Filter_Preamble
	 */
	public function setPreambleLength($length)
	{
		if (!is_numeric($length) || $length <= 0)
			throw new Zend_Filter_Exception('Length should be positive integer');
		
		$this->_preambleLength = intval($length);
		return $this;
	}

	/**
	 * Get prospective preamble length
	 *
	 * @return int
	 */
	public function getPreambleLength()
	{
		return $this->_preambleLength;
	}
	
	/**
	 * Perform preamble filter
	 *
	 * @param string $text
	 * @return string
	 */
	public function filter($text)
	{
		if(mb_strlen($text) <= $this->_preambleLength)
			return $text;
		preg_match('/\./', $text, $matches, PREG_OFFSET_CAPTURE, $this->_preambleLength * 0.8);
		if(!empty($matches))
			$match = $matches[0][1];
		if(empty($matches) || $match > $this->_preambleLength * 1.2) {
			preg_match_all('/[^a-zżółćęśąźń0-9]/', mb_substr($text, 0, $this->_preambleLength * 1.5), $matches, PREG_OFFSET_CAPTURE, $this->_preambleLength * 0.5);
			$match = $matches[0][(int)floor(sizeof($matches[0])/2)][1];
			if($match < $this->_preambleLength * 0.7 || $match > $this->_preambleLength * 1.3)
				$match = $this->_preambleLength;
		}
		
		$preamble = mb_substr($text, 0, $match + 1);
		if(!in_array(mb_substr($preamble, -1), array('.', '!', ';', ')', '"', '\'')) && $preamble != $text)
			$preamble = rtrim(mb_substr($preamble, 0, -1), '.,:!') . '...';
		$preamble = trim($preamble, '.-');
		
		return($preamble);
	}
}